package com.mall.user.services;

import com.mall.commons.tool.exception.ValidateException;
import com.mall.user.IVerifyService;
import com.mall.user.constants.SysRetCodeConstants;
import com.mall.user.dal.entitys.Member;
import com.mall.user.dal.entitys.UserVerify;
import com.mall.user.dal.persistence.MemberMapper;
import com.mall.user.dal.persistence.UserVerifyMapper;
import com.mall.user.dto.UserVerifyRequest;
import com.mall.user.dto.UserVerifyResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;

/**
 * @author hanshuai
 * @version 1.0
 * @description @TODO
 * @date 2021/12/11 22:25
 */
@Service
@Slf4j
public class VerifyServiceImpl implements IVerifyService {
    @Autowired
    UserVerifyMapper userVerifyMapper;

    @Autowired
    MemberMapper memberMapper;

    @Override
    public UserVerifyResponse verify(UserVerifyRequest userVerifyRequest) {
        UserVerifyResponse response = new UserVerifyResponse();
        Example example = new Example(Member.class);
        example.createCriteria().andEqualTo("username", userVerifyRequest.getUsername());

        Example verifyExample = new Example(UserVerify.class);
        verifyExample.createCriteria().andEqualTo("username", userVerifyRequest.getUsername()).andEqualTo("uuid", userVerifyRequest.getUuid());
        List<UserVerify> userVerifies = userVerifyMapper.selectByExample(verifyExample);
        //如果用户名和uuid不匹配 就抛出异常
        if (userVerifies.size() != 1) {
            response.setCode(SysRetCodeConstants.DATA_NOT_EXIST.getCode());
            response.setMsg(SysRetCodeConstants.DATA_NOT_EXIST.getMessage());
            return response;
        }
        //改变member 表中 verified 的状态
        Member member = new Member();
        member.setUpdated(new Date());
        member.setIsVerified("Y");
        memberMapper.updateByExampleSelective(member, example);

        //改变verify 表中 verified 的状态
        UserVerify userVerify = new UserVerify();
        userVerify.setIsVerify("Y");
        userVerifyMapper.updateByExampleSelective(userVerify, example);
        //打印日志信息
        log.info("用户  "+userVerifyRequest.getUsername()+"  激活成功");
        response.setCode(SysRetCodeConstants.SUCCESS.getCode());
        response.setMsg(SysRetCodeConstants.SUCCESS.getMessage());
        return response;
    }
}
